# -*- coding: utf-8 -*-
# flake8: noqa

import sys
import os
import time
import qiniu as Q
import qiniu.config
from watchdog.observers import Observer
from watchdog.events import RegexMatchingEventHandler
import confuse
from logzero import logger
if sys.platform == 'darwin':
    from pync import Notifier
import configparser


config = configparser.ConfigParser()
config.read('config.ini')

try:
    QINIU_ACCESS_KEY = config['QINIU']['ACCESS_KEY']
    QINIU_SECRET_KEY = config['QINIU']['SECRET_KEY']
    QINIU_BUCKET = config['QINIU']['BUCKET']
    QINIU_DOMAIN = config['QINIU']['DOMAIN']
    DC_HOME = config['DEFAULT']['path']
except KeyError as e:
    logger.inof("Missing configuration variable %s" % e)
    sys.exit(1)


def notify(msg):
    logger.info(msg)
    if sys.platform == 'darwin':
        Notifier.notify(msg)


class QN(object):
    def __init__(self, ak, sk):
        self.qn = Q.Auth(ak, sk)

    def upload_file(self, bucket, local, key=None):
        if not key:
            key = os.path.basename(local)
        token = self.qn.upload_token(bucket, key, 3600)
        ret, info = Q.put_file(token, key, local)
        return ret, info

    def delete_file(self, bucket, key):
        notify('Deleting %s from %s...' % (key, bucket))
        bm = qiniu.BucketManager(self.qn)
        _, info = bm.delete(bucket, key)
        if not info.ok():
            notify('Failed to delete file %s' % info)


class Monitor(object):
    def __init__(self, path):
        self.path = os.path.abspath(path)
        self.ob = Observer()

    def on_add(self, callback):
        self.ob.schedule(callback, self.path, recursive=True)

    def run(self):
        self.ob.start()
        self.ob.join()


class Handler(RegexMatchingEventHandler):
    def __init__(self, qn, bucket, domain, root, reg_ignore = []):
        super(Handler, self).__init__(ignore_regexes=reg_ignore,ignore_directories=True)
        self.qn = qn
        self.bucket = bucket
        self.domain = domain
        self.root = os.path.abspath(root)

    def on_created(self, event):
        # '/' makes sure that rel_path is relative
        rel_path = event.src_path.split(self.root + '/')[1]
        self.qn.upload_file(self.bucket, event.src_path, rel_path)
        notify('%s uploaded to "%s"' % (event.src_path, self.bucket))
        notify('direct link: http://%s' % os.path.join(self.domain, rel_path))

    def on_deleted(self, event):
        notify('deleting %s' % event.src_path)
        rel_path = event.src_path.split(self.root + '/')[1]
        self.qn.delete_file(self.bucket, rel_path)


def main(path):
    mon = Monitor(path)
    qn = QN(QINIU_ACCESS_KEY, QINIU_SECRET_KEY)
    mon.on_add(Handler(qn, QINIU_BUCKET, QINIU_DOMAIN, path))
    mon.run()


if __name__ == "__main__":
    main(DC_HOME)
